package com.biye.api.tool.ExcelTemplate;

import com.base.common.edu.entity.EduClass;
import com.base.common.edu.entity.StuContact;
import com.base.common.edu.entity.Student;
import com.base.common.edu.mapper.StuContactMapper;
import com.base.common.edu.mapper.StudentMapper;
import com.base.common.edu.util.Dateutil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

@Transactional
public class StuInfoImportThread implements Runnable{

    /***
     * 如果用了线程池，就不需要再使用信号量。根据时间情况使用synchronized(this)
     * ExecutorService executor = Executors.newFixedThreadPool(Thread_size);
     */
    private final Semaphore parallel = new Semaphore(10);

    private static Integer aaa=1;  // 定义一个线程共享变量

    private StudentMapper sd;
    private StuContactMapper stuContactMapper;
    private List<Student> list;
    private Map<String, String> class_mapping;
    private static SqlSessionFactory sqlSessionFactory;

    public StuInfoImportThread(List<Student> list, StudentMapper studentMapper, SqlSessionFactory sqlSessionFactory, Map<String, String> class_mapping, StuContactMapper stuContactMapper){
        this.list = list;
        this.sd=studentMapper;
        this.sqlSessionFactory=sqlSessionFactory;
        this.class_mapping = class_mapping;
        this.stuContactMapper = stuContactMapper;
    }

    @Override
    public void run() {
        synchronized(this){
            try {
                parallel.acquire();
                insert();
//                System.out.println("当前剩余通道数="+parallel.availablePermits());
                parallel.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void insert(){
        System.out.println(list.size() + " [ggj");
        for (Student student : list ){
            // 班级id
            String class_name = student.getEduClass().getClassName();
            String grade_year = student.getEduClass().getGradeYear();
            String class_no_ = Integer.toString(student.getEduClass().getClassNo());
            String dept_name = student.getEduClass().getDeptObject().getDeptName();
            StringBuffer strbuilder = new StringBuffer();
            strbuilder.append(class_name);
            strbuilder.append("@");
            strbuilder.append(grade_year);
            strbuilder.append("@");
            strbuilder.append(class_no_);
            strbuilder.append("@");
            strbuilder.append(dept_name);
            String class_id = class_mapping.get(strbuilder.toString());
//            System.out.println("[[[[["+strbuilder.toString());
//            System.out.println("]]]]]"+class_id);
            EduClass ec = new EduClass();
            ec.setClassId(class_id);
            student.setEduClass(ec);
            // 由于导入的时候将手机号装入了Email字段，所以要将Email字段更新
            // 取出手机号
            String phone = student.getEmail().split("###")[0];
            String email = student.getEmail().split("###")[1];
            student.setEmail(email);
            // 首先根据身份证号查询是否有该学生信息
            Student stu = new Student();
            stu.setSno(student.getSno());
            stu.setIdCard(student.getIdCard());
            stu.setEmail(student.getEmail());
            List<Student> students = sd.queryStudents(stu);
            // 若有该学生信息，则更新
            if ( students.size() > 0 ) {
                String student_id = students.get(0).getStuID();
                student.setStuID(student_id);
                sd.updateStudent(student);
                int i = stuContactMapper.judgeIsItExists(student_id, phone);
                if ( i < 1 ){
                    StuContact stu_c = new StuContact();
                    stu_c.setStudent(student);
                    stu_c.setMobile(phone);
                    stuContactMapper.addStuContact(stu_c);
                }
                continue;
            }
            // 若没有则新增,同时判断邮箱是否被占用, 被占用则略过信息创建，并打印
            else if ( sd.judgeIsItOccupied(student.getSno(), student.getIdCard(), student.getEmail()) > 0 ){
                System.out.println("该学生信息导入失败（学工号、身份证、邮箱号被占用）[Name：" + student.getStuName() + "][userIdcard：" + student.getIdCard() + "][userEmail：" + student.getEmail() + "][Time：" + Dateutil.getCurrentDateText() + "]");
                continue;
            }else {
                student.setActivateStatus(1);
                sd.saveStudent(student);
                int i = stuContactMapper.judgeIsItExists(student.getStuID(), phone);
                if (i < 1) {
                    StuContact stu_c = new StuContact();
                    stu_c.setStudent(student);
                    stu_c.setMobile(phone);
                    stuContactMapper.addStuContact(stu_c);
                }
            }
        }
        System.out.println("Thread-" + (aaa++) + " end of run");
    }

}
